<template>
  <div class="tabs-main">
    <a-tabs v-model="tabValue" :tabBarStyle="{ backgroundColor: '#fff', marginBottom: '6px', padding: '0px 8px' }"
      v-if="tabsItems && tabsItems.length>0" @change="changeTabs">
      <a-tab-pane v-for="item in tabsItems" :tab="item.title" :key="item.key" />
    </a-tabs>
    <a-row type="flex" style="flex-flow: inherit;" v-if="reloading">
      <a-col :flex="toggle ? '260px' : '30px'" style="margin-right: 12px;background-color: #fff;">
        <depart-tree :rootOpened="true" :multi="false" @ok="getTreeData" @toggleBool="toggleBool" />
      </a-col>
      <a-col flex="auto">
        <a-card :bordered="false" style="margin-bottom: 10px">
          <!-- 查询区域 -->
          <div class="table-page-search-wrapper">
            <a-form-model layout="inline" ref="ruleForm" :model="queryParam">
              <z-form-item :datas="fieldArr" :form="queryParam" :gutter="8"
                :submitAction="{ show: true, toggle: true, span: 6 }" @change="getChangeTime" @onSubmit="onQuery"
                @onReset="onResetForm" />
            </a-form-model>
          </div>
        </a-card>
        <a-card :bordered="false">
          <!-- 操作按钮区域 -->
          <div class="table-operator">
            <div>
              <a-button @click="handleExport">导出</a-button>
            </div>
          </div>
          <!-- 表格展示 -->
          <div class="table-page-content">
            <z-table ref="table" rowKey="id" :showAlert="false" :showSelection="true" :loading="loading"
              :columns="columns" :dataSource="pageData" @change="onTableChange" />
          </div>
          <!--弹窗区域-->
          <handle-modal ref="handleModalRef" @ok="modalFormOk" />
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script>
import departTree from '../../modules/departTree'
import handleModal from '../../modules/handleModal'
import * as serviceApi from '@/api/sjsk/clinicmanageService'
import { downLoadFileReader } from '@/utils/export-util/util'

export default {
  components: { departTree, handleModal },
  data() {
    return {
      tabValue: "",
      tabsItems: [
        { key: '', title: '待评估', },
        { key: 3, title: '已完成', },
      ],
      loading: false,
      reloading: true,
      toggle: true,
      queryParam: {},
      fieldArr: [
        { label: '吸毒人员姓名', prop: 'name', tagType: 'input', span: 8 },
        { label: '吸毒人员身份证', prop: 'identification', tagType: 'input', span: 8 },
        { label: '人员类型', prop: 'type', tagType: 'dict-select', dictCode: 'risk_level_person_type', span: 8, toggle: false },
        { label: '评估周期', prop: 'evaluationDate', tagType: 'range-picker', format: 'YYYY-MM-DD', span: 8, toggle: false },
        { label: '性别', prop: 'sex', tagType: 'dict-select', dictCode: 'sex', span: 8, toggle: false },
      ],
      columns: [
        {
          title: '姓名',
          dataIndex: 'realName',
          width: 60,
          align: 'center',
          customRender: text => {
            return <j-ellipsis value={text} length={14} />
          }
        },
        {
          title: '性别',
          dataIndex: 'sex',
          width: 60,
          align: 'center',
          customRender: text => {
            return this.$filterDictTextByCache('sex', text)
          }
        },
        {
          title: '身份证号',
          dataIndex: 'identityCard',
          width: 100,
          align: 'left',
          customRender: text => {
            return <j-ellipsis value={text} length={20} />
          }
        },
        {
          title: '联系电话',
          dataIndex: 'phone',
          width: 90,
          align: 'center',
          // customRender: text => {
          //   return <j-ellipsis value={text} length={14} />
          // }
        },
        {
          title: '人员类型',
          dataIndex: 'personType',
          width: 80,
          align: 'center',
          customRender: text => {
            return <j-ellipsis value={this.$filterDictTextByCache('risk_level_person_type', text)} length={14} />
          }
        },
        {
          title: '风险等级',
          dataIndex: 'currentRiskLevel',
          width: 80,
          align: 'center',
          customRender: text => {
            return <j-ellipsis value={this.$filterDictTextByCache('risk_category', text)} length={14} />
          }
        },
        {
          title: '管辖地区',
          dataIndex: 'householdTown',
          width: 110,
          align: 'center',
          customRender: text => {
            return <j-ellipsis value={text} length={14} />
          }
        },
        {
          title: '评估周期',
          dataIndex: 'evalCycle',
          width: 80,
          align: 'center'
        },
        {
          title: '操作',
          width: 60,
          align: 'center',
          dataIndex: 'action',
          customRender: (text, record, index) => {
            return (
              <a-space size={6}>
                {this.tabValue == "" && record.status == 1 ?
                  <a-badge dot>
                    <a-button type="link" style={'padding:0'} onClick={event => this.handleModal('risk-assessment-application', record)}>评估申请</a-button>
                  </a-badge>
                  : this.tabValue == "" && record.status == 4 ?
                    <a-button type="link" style={'padding:0'} onClick={event => this.handleModal('risk-assessment-application', record)}>重新申请</a-button>
                    :
                    <a-button type="link" style={'padding:0'} onClick={event => this.handleRouter(record)}>查看</a-button>
                }
              </a-space>
            )
          }
        }
      ],
      pageFilter: {
        pageNo: 1,
        pageSize: 10
      },
      pageData: {}
    }
  },
  watch: {
    'tabValue': {
      immediate: true,
      deep: true,
      handler(val) {
        console.log("1111111")
        console.log(val)
        let fieldItem = { label: '评估状态', prop: 'status', tagType: 'dict-select', dictCode: 'risk_level_assess', span: 8, toggle: false }
        let columnsItemOne = {
          title: '评估状态', dataIndex: 'status', width: 80, align: 'center', customRender: text => {
            return (
              <span class={text == 2 ? 'text_color_4' : text == 4 ? 'text_color_2' : ''}>
                <j-ellipsis value={this.$filterDictTextByCache('risk_level_assess', text)} length={14} />
              </span>
            )
          }
        }
        let columnsItemTwo = { title: '评估完成日期', dataIndex: 'evaluationEndDate', width: 100, align: 'center' }
        let fieldIndex = this.fieldArr.findIndex(item => item.prop === 'evaluationDate')
        let columnsIndex = this.columns.findIndex(item => item.dataIndex === 'evalCycle')
        if (val == "") {
          // 所属框-在评估周期项后，插入评估状态项
          this.fieldArr.splice(fieldIndex + 1, 0, fieldItem)
          // 表格表头--在评估周期项后，插入评估状态项
          let dataIndex = this.columns.findIndex(item => item.dataIndex === columnsItemTwo.dataIndex)
          this.columns.splice(columnsIndex + 1, dataIndex > 0 ? 1 : 0, columnsItemOne)
        } else {
          // 所属框-移除评估状态项
          this.fieldArr.splice(fieldIndex + 1, 1)
          // 表格表头--在评估周期项后，插入评估完成日期项
          let dataIndex = this.columns.findIndex(item => item.dataIndex === columnsItemOne.dataIndex)
          this.columns.splice(columnsIndex + 1, dataIndex > 0 ? 1 : 0, columnsItemTwo)
        }
      }
    },
    // 组织机构树-联动筛选人员列表
    'queryParam.departmentId'(newVal, oldVal) {
      this.modalFormOk()
    },
  },
  methods: {
    changeTabs() {
      this.reload()
      this.onResetForm()
    },
    onQuery() {
      this.pageFilter.pageNo = 1
      this.refreshTable()
    },
    onResetForm() {
      const queryParam = (({ departmentId }) => ({ departmentId }))(this.queryParam) //清空对象，只保留departmentId元素
      this.queryParam = queryParam
      this.pageFilter.pageNo = 1
      this.pageFilter.pageSize = 10
      this.refreshTable()
    },
    onTableChange(pagination, pageFilter, sorter) {
      this.pageFilter = Object.assign({}, this.pageFilter, pagination)
      this.refreshTable()
    },
    refreshTable() {
      this.$set(this.queryParam, 'status', this.tabValue)
      let { evaluationDate, ...dataParam } = this.queryParam // 剔除evaluationDate元素，dataParam最新的对象
      let queryParam = Object.assign({}, dataParam, this.pageFilter)
      this.loading = true
      serviceApi
        .getPageNewRiskLevelEval(queryParam)
        .then(res => {
          this.loading = false
          this.pageData = res.result ? res.result : {}
          this.$refs.table.onClearRowKeys()
          if (!res.success) this.$message.warn(res.message ? res.message : '请求失败')
        })
        .catch(e => {
          this.loading = false
          this.$message.warn('请求失败！')
        })
    },
    // 导出
    handleExport(record) {
      let that = this
      let selectList = this.$refs.table.getSelectedRows()
      let idList1 = selectList.map(v => v.id).filter(obj => obj !== null && obj !== undefined && obj !== '')
      let idList2 = record && Object.keys(record).length > 0 && record.id ? [record.id] : []
      let params = Object.assign(
        {},
        {
          idList: selectList.length > 0 ? idList1 : idList2,
          ...this.queryParam
        }
      )
      this.$confirm({
        title: `是否确认导出？`,
        okText: '确定',
        onOk() {
          serviceApi.exportRiskLevelEval(params).then(async res => {
            const fileName = '风险等级评估列表数据.xlsx'
            await downLoadFileReader(res, fileName)
            that.$refs.table.onClearRowKeys()
          })
        }
      })
    },
    handleRouter(record) {
      let id = record instanceof Object ? record.id : record
      let path = id ? `/examine/details/40/${id}` : ``
      this.$router.push({
        path: path,
        query: {},
      })
    },
    // 获取组件的时间， prop为对应的字段，date为选中的时间值
    getChangeTime(prop, date) {
      if (prop === 'evaluationDate') {
        this.$set(this.queryParam, 'evaluationStartDate', date[0])
        this.$set(this.queryParam, 'evaluationEndDate', date[1])
      }
    },
    // 弹窗成功接收
    modalFormOk() {
      this.onQuery()
    },
    // 弹窗操作
    handleModal(key, record) {
      this.$refs.handleModalRef.show(key, record)
    },
    /** 重新加载组件 */
    reload() {
      this.reloading = false
      this.$nextTick(() => (this.reloading = true))
    },
    // 获取部门id
    getTreeData(datas, id) {
      console.log(datas, id)
      this.$set(this.queryParam, 'departmentId', id)
    },
    toggleBool(bool) {
      console.log(bool)
      this.toggle = bool
    }
  }
}
</script>
<style scoped lang="less">
.text_color_1 {
  color: #70B603;
}

.text_color_2 {
  color: #d9001b;
}

.text_color_3 {
  color: #f59a23;
}

.text_color_4 {
  color: #02a7f0;
}

.text_color_5 {
  color: #aeaeae;
}
</style>
